package com.sisy.service.impl;

import com.sisy.common.DubboOrderService;
import com.sisy.common.OrderDO;
import com.sisy.exception.BaseException;
import com.sisy.mapper.OrderMapper;
import com.sisy.poji.AccountDO;
import com.sisy.poji.OrderCreateDTO;
import com.sisy.poji.StorageDO;
import com.sisy.service.OrderService;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author EJ
 * @date 2021-06-13 15:31
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DubboOrderService dubboOrderService;

    @Override
    public AccountDO getAccountByUserId(String userId) {
        return orderMapper.getAccountByUserId(userId);
    }

    @Override
    public AccountDO getAccountByUserIdUpdate(String userId) {
        return orderMapper.getAccountByUserIdUpdate(userId);
    }

    @Override
    @GlobalLock
    public StorageDO getStorageByCommodityCode(String commodityCode) {
        return orderMapper.getStorageByCommodityCode(commodityCode);
    }

    @Override
    @GlobalLock
    public StorageDO getStorageByCommodityCodeUpdate(String commodityCode) {
        return orderMapper.getStorageByCommodityCodeUpdate(commodityCode);
    }

    @Override
    @GlobalTransactional
    public void createOrder(OrderCreateDTO orderCreateDTO) {
        // 扣库存
        int storageStatus = orderMapper.updateStorageCount(orderCreateDTO.getCount(), orderCreateDTO.getCommodityCode());
        if (storageStatus == 0) {
            throw new BaseException("库存不足");
        }

        // 生成订单
        StorageDO commodity = orderMapper.getStorageByCommodityCode(orderCreateDTO.getCommodityCode());
        OrderDO orderDO = new OrderDO();
        BeanUtils.copyProperties(orderCreateDTO, orderDO);
        orderDO.setMoney(orderCreateDTO.getCount() * commodity.getPrice());
        dubboOrderService.createOrder(orderDO);
    }
}
